<template>
  <UploadImgWrapper>
    <a-upload
      list-type="picture-card"
      class="avatar-uploader"
      :customRequest="handleUpload"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :accept="accept"
    >
      <div v-if="url" class="img">
        <img :src="url" alt="avatar" :style="imgStyle"/>
        <a-icon v-if="uploading" type="loading" />
      </div>
      <div v-else class="to-upload">
        <a-icon :type="uploading ? 'loading' : 'upload'" />
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
    <div class="upload-info">{{text}}</div>
  </UploadImgWrapper>
</template>

<script>
import { UploadImgWrapper } from './style'
import { getImgBase64 } from '@/utils/index'

export default {
  name: 'upload-img',
  components: {
    UploadImgWrapper,
  },
  props: {
    url: {
      type: String,
      default: '',
    },
    imgStyle: {
      type: String,
      default: 'width: 200px; height: 200px; object-fit: contain;',
    },
    text: {
      type: String,
      default: '图片格式必须为.png.jpeg.jpg，建议200*200px，可修改',
    },
  },
  data () {
    return {
      file: null,
      uploading: false,
      accept: 'image/png,image/jpeg,image/jpg',
    }
  },
  methods: {
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isJpgOrPng) {
        this.$message.error('图片格式错误!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小超过2M!')
      }
      this.file = file
      return isJpgOrPng && isLt2M
    },
    handleUpload () {
      if (this.uploading) return false

      this.uploading = true
      getImgBase64(this.file)
        .then(base64 => {
          this.$store.dispatch('uploadImg', {
            imgBase64: base64,
          })
            .then((res) => {
              this.uploading = false
              this.$emit('change', res.result)
            })
            .catch(() => {
              this.uploading = false
            })
        })
    },
  },
}
</script>
